package com.platform.service;

import com.alibaba.fastjson.JSONObject;
import com.platform.dao.ApiRemitMapper;
import com.platform.dao.ApiUserMapper;
import com.platform.entity.RemitVo;
import com.platform.entity.UserVo;
import com.platform.utils.Query;
import com.platform.utils.RRException;
import com.platform.validator.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ApiRemitService {
    @Autowired
    private ApiRemitMapper remitDao;
    @Autowired
    private ApiUserMapper userDao;

    @Transactional
    public RemitVo submit(JSONObject jsonParam, UserVo loginUser) {
        String remit_fee = jsonParam.getString("remit_fee");


        Assert.isBlank(remit_fee, "金额不能为空");
        BigDecimal remit_fees = new BigDecimal(remit_fee);
        UserVo userVo = userDao.queryObject(loginUser.getUserId());
        if(remit_fees.compareTo(userVo.getBalance_fee()) == 1){
            throw new RRException("提取金额不能超过当前账户总额");
        }
        RemitVo remitVo = new RemitVo();
        remitVo.setNideshop_user(loginUser.getUserId());
        remitVo.setApply_time(new Date());
        remitVo.setRemit_fee(remit_fees);
        remitVo.setRemit_type(0);
        remitVo.setRemit_status(0);
        userVo.setBalance_fee(userVo.getBalance_fee().subtract(remit_fees));
        int userNum = userDao.update(userVo);
        remitDao.save(remitVo);
        if(null == remitVo.getId() || userNum!=1){
            throw new RRException("提款失败，请重试");
        }
        return remitVo;
    }

    public void updateRemit(RemitVo remitVo) {
        remitDao.update(remitVo);
    }

    public List<RemitVo> queryRemitList(Map<String,Object> map) {
        return remitDao.queryRemitList(map);
    }

    public int queryTotal(Query query) {
        return remitDao.queryTotal(query);
    }
}
